package com.itheima.manager;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.service.db.AdminService;
import com.itheima.util.JwtUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Component
public class SoulManager {


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @DubboReference
    AdminService adminService;

    public ShearCaptcha sendCode(String username) {

        // String numbers = RandomUtil.randomNumbers(6);
        //
        // numbers = "123456";

        ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(200, 100);



        stringRedisTemplate.opsForValue().set("soul_telephone:"+username,shearCaptcha.getCode(), Duration.ofMinutes(5));

        return shearCaptcha;
    }

    public ResponseEntity login(String username, String password, String code) {

        String redisCode = stringRedisTemplate.opsForValue().get("soul_telephone:" + username);

        if (!StrUtil.equalsIgnoreCase(redisCode,code)) {
            return ResponseEntity.ok("0");
        }

        Admin byUsername = adminService.findByUsername(username);

        if (byUsername==null) {

            return ResponseEntity.ok("2");
        }

        if (!StrUtil.equals(byUsername.getPassword(), SecureUtil.md5(password))) {
            return ResponseEntity.ok("1");
        }

        //byUsername.setPassword(null);
        //String token = JwtUtil.createToken(BeanUtil.beanToMap(byUsername));

        //stringRedisTemplate.opsForValue().set("soul_token:"+token, JSON.toJSONString(byUsername),Duration.ofHours(1));



        return ResponseEntity.ok(8888);
    }
}
